import { ref, onMounted } from 'vue'
import {
    getFactoryProcurementListApi,
    getFactoryProcurementDetailApi,
    getFactoryProcurementPricesApi,
    type FactoryProcurementInfo,
    type FactoryProcurementListResponse,
    type FactoryProcurementPageQuery,
    type FactoryProcurementPricesResponse,
    type ApiResponse
} from '~/server/factoryProcurementApi'
import { PageQuery } from '~/types/global'

export const useFactoryProcurement = () => {
    const loading = ref(false)
    const procurementList = ref<FactoryProcurementInfo[]>([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    /**
     * 获取工厂收购列表
     * @param params 查询参数
     * @returns 工厂收购列表数据
     */
    const fetchProcurementList = async (params?: Partial<PageQuery & { keyword?: string; status?: number }>) => {
        try {
            loading.value = true
            const queryParams: FactoryProcurementPageQuery = {
                page: params?.page || currentPage.value,
                limit: params?.limit || pageSize.value,
                keyword: params?.keyword,
                status: params?.status
            }

            const response = await getFactoryProcurementListApi(queryParams)
            console.log('工厂收购API原始响应:', response)

            // 根据实际API返回的数据结构处理
            const apiData = response.data?.value || response.data || response
            console.log('处理后的数据:', apiData)

            // 检查响应结构
            if (apiData && typeof apiData === 'object') {
                if (apiData.code === 200 && apiData.data) {
                    const data = apiData.data as FactoryProcurementListResponse
                    total.value = data?.total || 0
                    const baseList = data?.list || []
                    const detailResults = await Promise.allSettled(
                        baseList.map((item: any) =>
                            getFactoryProcurementPricesApi({ factoryId: item.id, page: 1, limit: 50 })
                        )
                    )
                    const normalize = (base: any, detailRaw: any): FactoryProcurementInfo => {
                        const detail = detailRaw?.data?.value || detailRaw?.data || detailRaw || {}
                        const result: any = {}
                        result.id = detail?.id ?? base?.id
                        result.name = detail?.name ?? base?.name ?? base?.factoryName ?? ''
                        result.factoryName = detail?.factoryName ?? base?.factoryName ?? result.name ?? ''
                        result.businessHours = detail?.businessHours ?? base?.businessHours ?? ''
                        result.updateTime = detail?.updateTime ?? base?.updateTime ?? ''
                        result.province = detail?.province ?? base?.province ?? ''
                        result.city = detail?.city ?? base?.city ?? ''
                        result.district = detail?.district ?? base?.district ?? ''
                        result.addressDetail = detail?.addressDetail ?? base?.addressDetail ?? detail?.address ?? base?.address ?? ''
                        result.mobilePhone = detail?.mobilePhone ?? base?.mobilePhone ?? base?.landlinePhone ?? detail?.contactPhone ?? ''
                        result.description = detail?.description ?? base?.description ?? ''
                        const rawPriceList = Array.isArray(detail?.list) ? detail.list : []
                        const priceList = rawPriceList.map((raw: any) => ({
                            id: raw?.id ?? 0,
                            merId: raw?.merId ?? 0,
                            gradeName: raw?.gradeName ?? raw?.grade ?? '',
                            sizeSpec: raw?.sizeSpec ?? '',
                            productName: raw?.productName ?? '',
                            purchasePrice: raw?.purchasePrice ?? '',
                            qualityRequirements: raw?.qualityRequirements ?? '',
                            priceUnit: raw?.priceUnit ?? '',
                            startDate: raw?.startDate ?? '',
                            endDate: raw?.endDate ?? '',
                            status: !!raw?.status,
                            isDel: !!raw?.isDel,
                            createTime: raw?.createTime ?? '',
                            updateTime: raw?.updateTime ?? raw?.quoteDate ?? ''
                        }))
                        result.procurementItems = priceList.length
                            ? priceList
                            : Array.isArray(detail?.procurementItems)
                                ? detail.procurementItems
                                : []
                        if (!result.updateTime) {
                            result.updateTime = priceList[0]?.updateTime || ''
                        }
                        // 报价有效期（仅显示到“年月日”）
                        const validStart = priceList[0]?.startDate || ''
                        const validEnd = priceList[0]?.endDate || ''
                        const displayStart = validStart ? validStart.slice(0, 10) : ''
                        const displayEnd = validEnd ? validEnd.slice(0, 10) : ''
                        result.quoteValidStart = displayStart
                        result.quoteValidEnd = displayEnd
                        result.quoteValidPeriod = displayStart && displayEnd ? `${displayStart} - ${displayEnd}` : ''
                        result.coverImage = detail?.coverImage ?? base?.coverImage
                        result.companyTypeTag = detail?.companyTypeTag ?? base?.companyTypeTag
                        return result as FactoryProcurementInfo
                    }
                    const enriched = baseList.map((base, idx) => {
                        const res = detailResults[idx]
                        return res.status === 'fulfilled' ? normalize(base, res.value) : normalize(base, {})
                    })
                    procurementList.value = enriched
                    return { ...data, list: enriched }
                } else if (apiData.list) {
                    const data = apiData as FactoryProcurementListResponse
                    total.value = data.total || 0
                    const baseList = data.list || []
                    const detailResults = await Promise.allSettled(
                        baseList.map((item: any) =>
                            getFactoryProcurementPricesApi({ factoryId: item.id, page: 1, limit: 50 })
                        )
                    )
                    const normalize = (base: any, detailRaw: any): FactoryProcurementInfo => {
                        const detail = detailRaw?.data?.value || detailRaw?.data || detailRaw || {}
                        const result: any = {}
                        result.id = detail?.id ?? base?.id
                        result.name = detail?.name ?? base?.name ?? base?.factoryName ?? ''
                        result.factoryName = detail?.factoryName ?? base?.factoryName ?? result.name ?? ''
                        result.businessHours = detail?.businessHours ?? base?.businessHours ?? ''
                        result.updateTime = detail?.updateTime ?? base?.updateTime ?? ''
                        result.province = detail?.province ?? base?.province ?? ''
                        result.city = detail?.city ?? base?.city ?? ''
                        result.district = detail?.district ?? base?.district ?? ''
                        result.addressDetail = detail?.addressDetail ?? base?.addressDetail ?? detail?.address ?? base?.address ?? ''
                        result.mobilePhone = detail?.mobilePhone ?? base?.mobilePhone ?? base?.mobilePhone ?? detail?.mobilePhone ?? ''
                        result.landlinePhone = detail?.landlinePhone ?? base?.landlinePhone ?? base?.landlinePhone ?? detail?.landlinePhone ?? ''
                        result.description = detail?.description ?? base?.description ?? ''
                        const rawPriceList = Array.isArray(detail?.list) ? detail.list : []
                        const priceList = rawPriceList.map((raw: any) => ({
                            id: raw?.id ?? 0,
                            merId: raw?.merId ?? 0,
                            gradeName: raw?.gradeName ?? raw?.grade ?? '',
                            sizeSpec: raw?.sizeSpec ?? '',
                            productName: raw?.productName ?? '',
                            purchasePrice: raw?.purchasePrice ?? '',
                            qualityRequirements: raw?.qualityRequirements ?? '',
                            priceUnit: raw?.priceUnit ?? '',
                            startDate: raw?.startDate ?? '',
                            endDate: raw?.endDate ?? '',
                            status: !!raw?.status,
                            isDel: !!raw?.isDel,
                            createTime: raw?.createTime ?? '',
                            updateTime: raw?.updateTime ?? raw?.quoteDate ?? ''
                        }))
                        result.procurementItems = priceList.length
                            ? priceList
                            : Array.isArray(detail?.procurementItems)
                                ? detail.procurementItems
                                : []
                        if (!result.updateTime) {
                            result.updateTime = priceList[0]?.updateTime || ''
                        }
                        // 报价有效期（仅显示到“年月日”）
                        const validStart = priceList[0]?.startDate || ''
                        const validEnd = priceList[0]?.endDate || ''
                        const displayStart = validStart ? validStart.slice(0, 10) : ''
                        const displayEnd = validEnd ? validEnd.slice(0, 10) : ''
                        result.quoteValidStart = displayStart
                        result.quoteValidEnd = displayEnd
                        result.quoteValidPeriod = displayStart && displayEnd ? `${displayStart} - ${displayEnd}` : ''
                        result.coverImage = detail?.coverImage ?? base?.coverImage
                        result.companyTypeTag = detail?.companyTypeTag ?? base?.companyTypeTag
                        return result as FactoryProcurementInfo
                    }
                    const enriched = baseList.map((base, idx) => {
                        const res = detailResults[idx]
                        return res.status === 'fulfilled' ? normalize(base, res.value) : normalize(base, {})
                    })
                    procurementList.value = enriched
                    return { ...data, list: enriched }
                } else {
                    console.error('未知的API响应格式:', apiData)
                    throw new Error('API响应格式不正确')
                }
            } else {
                throw new Error('API调用失败: 响应数据格式错误')
            }
        } catch (error) {
            console.error('获取工厂收购列表失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取工厂收购详情
     * @param id 工厂收购ID
     * @returns 工厂收购详情数据
     */
    const fetchProcurementDetail = async (id: number) => {
        try {
            const response = await getFactoryProcurementDetailApi(id)
            console.log('工厂收购详情API响应:', response)
            return response.data?.value || response.data || response
        } catch (error) {
            console.error('获取工厂收购详情失败:', error)
            throw error
        }
    }

    /**
     * 刷新工厂收购列表
     */
    const refreshProcurementList = async () => {
        await fetchProcurementList({
            page: currentPage.value,
            limit: pageSize.value
        })
    }

    /**
     * 处理分页变化
     * @param page 页码
     * @param size 每页数量
     */
    const handlePageChange = async (page: number, size?: number) => {
        currentPage.value = page
        if (size) {
            pageSize.value = size
        }
        await refreshProcurementList()
    }

    /**
     * 搜索工厂收购
     * @param keyword 关键词
     */
    const searchProcurements = async (keyword: string) => {
        currentPage.value = 1
        await fetchProcurementList({
            page: 1,
            limit: pageSize.value,
            keyword
        })
    }

    /**
     * 按状态筛选工厂收购
     * @param status 状态
     */
    const filterByStatus = async (status: number) => {
        currentPage.value = 1
        await fetchProcurementList({
            page: 1,
            limit: pageSize.value,
            status
        })
    }

    return {
        loading,
        procurementList,
        total,
        currentPage,
        pageSize,
        fetchProcurementList,
        fetchProcurementDetail,
        refreshProcurementList,
        handlePageChange,
        searchProcurements,
        filterByStatus
    }
}
